package com.wangtianxiang.rabbitmq.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.util.Set;

/**
 *  
 *  fastjson 工具
 * @author lgyu4
 *
 */
public class JSONObjectUtil {
	

	/**
	 * convert class {@code A } to  class {@code B}
	 * @param source data
	 * @param c target class
	 * @return class {@code B} type data
	 */
	public static <A,B> B convert(A source, Class<B> c){
		return JSONObject.parseObject(JSONObject.toJSONString(source),c);
	}
	
	/**
	 * mere JSONObject (the method may change the {@code soucre} or {@code target} param)
	 * @param source the source JSONObject you have
	 * @param target the tagert JSONObject you want to merge
	 * @return the merged JSONObject
	 */
	public static JSONObject merge(JSONObject source, JSONObject target) {
		if (null == target || target.isEmpty()) {
			return null==source?target:source;
		}
		if (null == source||source.isEmpty() || source == target) {
			return target;
		}
		Set<String> keys =source.keySet();
		keys.forEach(key->{
			Object tarAttr = target.get(key);
			if(null==tarAttr){
				target.put(key, source.get(key));
				return;
			}
			if(tarAttr instanceof JSONObject){
				Object srcAttr = source.get(key);
				if(null!=srcAttr){
					if(srcAttr instanceof JSONObject){
						merge((JSONObject)srcAttr, (JSONObject)tarAttr);
					}
				}
			}else if(tarAttr instanceof JSONArray){
				Object srcAttr = source.get(key);
				if(null!=srcAttr){
					if(srcAttr instanceof JSONArray){
						//if the value is jsonarray just add all together!
						((JSONArray)tarAttr).addAll((JSONArray)srcAttr);
					}
				}
			}
			
		});
		return target;
	}
}
